/**
 * 
 * @Author: biubiu0002
 * @Date: 2021-04-26 11:41
 **/

#include "Student.h"
#include "StudentMapper.h"
#include "GlobalFile.h"
#include "fstream"
#include "iostream"
#include "sstream"
#include "list"
#include "vector"
using namespace std;



vector<Student> StudentMapper::selectStudentByClass(string classId) {
    vector<Student> resultList;
    list<Student> studentList =  this->getStudentList();
    for(Student student:studentList){
        if(student.getClassId()==classId){
            resultList.push_back(student);
        }
    }
    return resultList;
}

list<Student> StudentMapper::loadStudentList(){
    list<Student> stuList;
    string line;
    string field;

    fstream ifs("../../resource/Student.txt",ios::in|ios::out);
    if(!ifs){
        cout<<"../../resource/Student.txt"<<"文件打开失败"<<endl;
    }
    while(getline(ifs,line)){
        Student stu;
        vector<string> infoList;
        istringstream iss(line);
        while(iss>>field)
            infoList.push_back(field);
        stu.setId(infoList[0]);
        stu.setName(infoList[1]);
        stu.setClassId(infoList[2]);
        stu.setGender(infoList[3]);
        stu.setAge(stoi(infoList[4]));
        stu.setDormNo(infoList[5]);
        stu.setPhoneNumber(infoList[6]);
        stuList.push_back(stu);
    }
    ifs.close();
    return stuList;


}

int StudentMapper::batchInsertStudent(list<Student> &studentList) {
    ofstream ofs("../../resource/Student.txt",ios::out);
    if(!ofs){
        cout<<"Student.txt文件打开失败!"<<endl;
    }
    for(Student stu:studentList){
        ofs<<stu.getId()<<" ";
        ofs<<stu.getName()<<" ";
        ofs<<stu.getClassId()<<" ";
        ofs<<stu.getGender()<<" ";
        ofs<<stu.getAge()<<" ";
        ofs<<stu.getDormNo()<<" ";
        ofs<<stu.getPhoneNumber()<<endl;
    }
    return 0;
}

int StudentMapper::checkId(std::string studentId) {
    list<Student> studentList = this->loadStudentList();
    for(Student student:studentList){
        if(student.getId()==studentId){
            return 1;
        }
    }
    return 0;
}



const list<Student> &StudentMapper::getStudentList() const {
    return studentList;
}

void StudentMapper::setStudentList(const list<Student> &studentList) {
    StudentMapper::studentList = studentList;
}

StudentMapper::StudentMapper() {
    this->setStudentList(this->loadStudentList());
}

StudentMapper::~StudentMapper() {

}
